package com.lhg.serve;


import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.Map;

public class HttpResponseHandler {

   public static String build(HttpResponse httpResponse){
      StringBuilder builder = new StringBuilder();
      builder.append(httpResponse.getProtocol()).append(" ")
              .append(httpResponse.getCode()).append(" ")
              .append(httpResponse.getMessage()).append("\r\n");
      for (Map.Entry<String,String> entry: httpResponse.getHeaders().entrySet()){
         builder.append(entry.getKey()).append(": ").append(entry.getValue()).append("\r\n");
      }

      builder.append("\r\n");

      if (httpResponse.getBody() != null){
         builder.append(httpResponse.getBody());
      }
      return builder.toString();
   }

   public static void write(OutputStream outputStream,HttpResponse httpResponse){
      String response = build(httpResponse);

      try {
         outputStream.write(response.getBytes());
         outputStream.flush();
      } catch (IOException e) {
         e.printStackTrace();
      }

   }
}
